package com.edu.neusoft.phone_sale.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.neusoft.phone_sale.common.ResponseResult;
import com.edu.neusoft.phone_sale.common.enums.AppHttpCodeEnum;
import com.edu.neusoft.phone_sale.dto.UserDto;
import com.edu.neusoft.phone_sale.entity.User;
import com.edu.neusoft.phone_sale.mapper.UserMapper;
import com.edu.neusoft.phone_sale.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 用户登录功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(UserDto dto, HttpSession session) {
        //1.正常登录：用户名和密码
        if (StringUtils.isNotBlank(dto.getUsername()) && StringUtils.isNotBlank(dto.getPassword())) {
            //1.1 根据手机号查询用户信息
            User dbUser = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, dto.getUsername()));
            if (dbUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户信息不存在");
            }

            //1.2 校验密码
            String password = dto.getPassword();
            String dbUserPassword = dbUser.getPassword();
            if (password.equals(dbUserPassword)) {
                session.setAttribute("loginUser", dbUser);
                //日志记录
                log.info("session:----------------" + session.getAttribute("loginUser"));
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            //2.用户名或密码为空，登录失败
            return ResponseResult.errorResult(AppHttpCodeEnum.ERROR_USERNAME_PASSWORD_EMPTY);
        }
    }

}
